<?php

use Illuminate\Database\Eloquent\SoftDeletingTrait;

class Product extends Eloquent{

	use SoftDeletingTrait;

	public $timestamps   = true;
	protected $dates     = ['deleted_at'];
	protected $table     = 'product';
	protected $validator = null;

	public function saveData($data){
		$product = new Product;

		if(isset($data['id']) && $data['id'] > 0){
			$product = Product::firstOrNew(array('id' => $data['id']));
		}

		$product->name        = $data['productname'];
		$product->alias       = $data['alias'];
		$product->sku         = $data['sku'];
		$product->image       = $data['image'];
		$product->description = $data['description'];
		$product->category    = $data['type'];
		$product->brand       = $data['brand'];
		$product->price       = $data['price'];
		$product->quantity    = 0;
		$product->save();
		
		Cache::forget('product-all-data');

		return $product;
	}

	public function getAllData(){
		if(!Cache::has('product-all-data')){
			$data = DB::table('product as p')
					->join('taxonomy as c', 'p.category', '=', 'c.id')
					->join('taxonomy as b', 'p.brand', '=', 'b.id')
					->whereNull('p.deleted_at')
					->orderBy('p.created_at', 'desc')
					->select('p.id', 'p.name', 'p.image', 'c.taxonomy as type', 'b.taxonomy as brand', 'p.name', 'p.created_at', 'p.updated_at', 'p.quantity')
					->get();
			Cache::put('product-all-data', $data, 30);
		}

		$data = Cache::get('product-all-data');

		return $data;
	}

	public function validator($data){
		$rules = array(
			'productname' => array('required', 'alpha_num_spaces'),
			'alias'       => array('alpha_num_spaces'),
			'sku'         => array('required', 'alpha_num_spaces'),
			'price'       => array('required', 'numeric', 'min:0'),
			'image'       => array('image'),
			'description' => array('required'),
			);

		$this->validator = Validator::make($data, $rules);

		return $this->validator;
	}

	public function getErrorMessages(){
		$messages = $this->validator->messages();
		
		$result   = array();

		foreach($messages->all() as $m){
			$result[]['message'] = $m;
		}

		return $result;
	}
}
